﻿using System.Data;

namespace DataScripter.Database
{
    public class ForeignKeyInfo : IMetadataReader, IForeignKey
    {
        public ForeignKeyInfo(string name, string schemaName, string tableName, string columnName, string referencedSchemaName, string referencedTableName, string referencedColumnName)
        {
            Name = name;
            SchemaName = schemaName;
            TableName = tableName;
            ColumnName = columnName;
            ReferencedSchemaName = referencedSchemaName;
            ReferencedTableName = referencedTableName;
            ReferencedColumnName = referencedColumnName;
        }

        public ForeignKeyInfo()
        { }

        public string Name { get; private set; }

        public string SchemaName { get; private set; }
        public string TableName { get; private set; }
        public IForeignKey CreateReverseInMemoryForeignKey()
        {
            return new ForeignKeyInfo(Name,
                                      ReferencedSchemaName,
                                      ReferencedTableName,
                                      ReferencedColumnName,
                                      SchemaName,
                                      TableName,
                                      ColumnName);
        }

        public string ColumnName { get; private set; }

        public string ReferencedSchemaName { get; private set; }
        public string ReferencedTableName { get; private set; }
        public string ReferencedColumnName { get; private set; }

        public override string ToString()
        {
            return ReferencedSchemaName + "." + ReferencedTableName + " (" + ColumnName + ") (" + Name + ")";
        }

        public void InitializeMetadata(IDataReader reader)
        {
            Name = reader.GetString("FOREIGN_KEY_NAME");
            SchemaName = reader.GetString("SCHEMA_NAME");
            TableName = reader.GetString("TABLE_NAME");
            ColumnName = reader.GetString("COLUMN_NAME");
            ReferencedSchemaName = reader.GetString("REFERENCED_SCHEMA_NAME");
            ReferencedTableName = reader.GetString("REFERENCED_TABLE_NAME");
            ReferencedColumnName = reader.GetString("REFERENCED_COLUMN_NAME");
        }

    }
}